package com.webflux.service;


import com.webflux.dao.ProductRepository;
import com.webflux.entity.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

@Service
public class ProductService {

    @Autowired
    private ProductRepository productRepository;



    public Mono<Product> save(Product product){
        return productRepository.save(product);
    }

    public Mono<Product> findById(Integer id){
        return productRepository.findById(id).switchIfEmpty(Mono.empty());
    }

    public Mono<Void> delete(Integer id){
        return productRepository.findById(id).flatMap(productRepository::delete);
    }

    public Flux<Product> findAll(){
        return productRepository.findAll();
    }

    public Mono<Product> updateById(Product product){

        return productRepository.existsById(product.getId()).flatMap(item ->{
            if(item){
                return productRepository.save(product);
            }
            return Mono.empty();
        });
    }





}
